package com.bjSoft.regressionTestTool.TestSelection;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

import util.Arquivo;
import cfg.Indexer;

import java.util.HashMap;
import java.util.List;

public class RegressionTestSelect {
	
	private HashMap<String, List<String>> testsInfo;
	
	public RegressionTestSelect() {
		this.testsInfo = new HashMap<String, List<String>>();
	}
	
	public HashMap<String, List<String>> selectTestCases(IProject project) throws CoreException, TestSelectionException, ClassNotFoundException {
		IFolder newCFGs = project.getFolder("new_CFGs");
		if (!newCFGs.exists()) {
			throw new TestSelectionException("ERROR, reading newCFG folder");
		}
		IResource[] members = newCFGs.members();
		IFile coverageInfo = project.getFile("coverageFile.txt");
		
		for (int i = 0; i < members.length; i++) {
			if (members[i] instanceof IFile) {
				Arquivo arq = 
					new Arquivo(coverageInfo.getLocation().toOSString(), "outfake");
				Indexer indexer = new Indexer(arq);
				IFile newCFGFile = (IFile) members[i];
				IFile covCFGFile = this.getCovCFGFile(newCFGFile, project);
				indexer.assertDangerousMethods(
						covCFGFile.getLocation().toOSString(), 
						newCFGFile.getLocation().toOSString());
				List<String> testCases = indexer.returnTestCasesToBeRun();
				String className = covCFGFile.getName().substring(
						0, covCFGFile.getName().length() - 4);
				testsInfo.put(className, testCases);			
			}
		}
		return this.testsInfo;			
	}
	
	private IFile getCovCFGFile(IFile newCFGFile, IProject project) throws CoreException {
		IFolder covCFGfolder = project.getFolder("coverage_CFGs");
		IResource[] members = covCFGfolder.members();
		IFile covCFGfile = null;
		for (int i = 0; i < members.length; i++) {
			if (members[i] instanceof IFile) {
				IFile temp = (IFile) members[i];
				if (temp.getName().equalsIgnoreCase(newCFGFile.getName())) {
					return temp;
				}
			}
		}
		return covCFGfile;
	}
}
